﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SPMS.Common
{
    /// <summary>
    /// 组合要求权限定义。
    /// </summary>
    public sealed class CompositionPermissionRequirement : IPermissionRequirement
    {
        #region ---Constructor

        /// <summary>
        /// 初始化类型<see cref="CompositionPermissionRequirement" />的新实例。
        /// </summary>
        /// <param name="leftRequirement">权限要求。</param>
        /// <param name="rightRequirement">权限要求。</param>
        /// <param name="relationship">权限要求之间的关联关系。</param>
        /// <exception cref="System.ArgumentNullException">当<see cref="leftRequirement"/>或者<see cref="rightRequirement"/>为<c>null</c>时，抛出此异常。</exception>
        public CompositionPermissionRequirement(IPermissionRequirement leftRequirement, IPermissionRequirement rightRequirement, CompositionRelationship relationship = CompositionRelationship.Or)
        {
            //判断参数
            if (null == leftRequirement)
            {
                //抛出异常
                throw new ArgumentNullException("leftRequirement");
            }

            if (null == rightRequirement)
            {
                //抛出异常
                throw new ArgumentNullException("rightRequirement");
            }

            //保存属性
            this.m_LeftRequirement = leftRequirement;
            this.m_RightRequirement = rightRequirement;
            this.m_Relationship = relationship;
        }

        #endregion

        #region ---IPermissionRequirement

        /// <summary>
        /// 判断当前登录用户是否满足功能权限要求。
        /// </summary>
        /// <param name="principal">窗体认证用户信息。</param>
        /// <returns>
        /// 如果满足，则返回<c>true</c>，否则返回<c>false</c>。
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public bool IsValid(FormsPrincipal principal)
        {
            //判断组合关系
            if (this.m_Relationship == CompositionRelationship.And)
            {
                return this.m_LeftRequirement.IsValid(principal) && this.m_RightRequirement.IsValid(principal);
            }
            else
            {
                return this.m_LeftRequirement.IsValid(principal) | this.m_RightRequirement.IsValid(principal);
            }
        }

        #endregion

        #region ---Field

        /// <summary>
        /// 权限要求。
        /// </summary>
        private IPermissionRequirement m_LeftRequirement;

        /// <summary>
        /// 权限要求。
        /// </summary>
        private IPermissionRequirement m_RightRequirement;

        /// <summary>
        /// 组合关系。
        /// </summary>
        private CompositionRelationship m_Relationship;

        #endregion
    }
}
